package com.sd.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

public class JxlsExcelUtil {

	/**
	 * 模板导出
	 * @param response
	 * @param datamap 数据
	 * @param modelname analysis.xlsx
	 * @param filename 统计分析
	 */
	public void export(HttpServletResponse response,Map<String, Object> datamap,String modelname,String filename) {
		InputStream in = null;
		try {
			in = new FileInputStream(JxlsExcelUtil.class.getClassLoader().getResource("/").getPath() + "excel/"+modelname);

			XLSTransformer transformer = new XLSTransformer();

			XSSFWorkbook wb = (XSSFWorkbook) transformer.transformXLS(in, datamap);
			
			//加入图片
			
			//
			writeStream(filename+System.currentTimeMillis(), wb, response); 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 输出流
	 * 
	 * @param filename
	 * @param wb
	 * @param response
	 */
	public void writeStream(String filename, Workbook wb, HttpServletResponse response) {
		try {
			filename += ".xlsx";

			filename.replaceAll("/", "-");
			filename = new String(filename.getBytes("gb2312"), "ISO8859-1" );
			response.reset();
			response.resetBuffer();
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + filename);
			response.setContentType("application/octet-stream;charset=UTF-8");

			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	

    /**  
     * 文件下载  
     * @param response  
     * @param path  
     */  
    private void downFile(HttpServletResponse response, String path,String filename) {
        try {
            File file = new File(path);   
            if (file.exists()) {   
                InputStream ins = new FileInputStream(path);   
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面   
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流   
                BufferedOutputStream bouts = new BufferedOutputStream(outs);   
                response.setContentType("application/x-download");// 设置response内容的类型   
                response.setHeader(   
                        "Content-disposition",   
                        "attachment;filename="  
                                + URLEncoder.encode(filename+".zip", "UTF-8"));// 设置头部信息   
                int bytesRead = 0;   
                byte[] buffer = new byte[8192];   
                // 开始向网络传输文件流   
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {   
                    bouts.write(buffer, 0, bytesRead);   
                }   
                bouts.flush();// 这里一定要调用flush()方法   
                ins.close();   
                bins.close();   
                outs.close();   
                bouts.close();   
            }
        } catch (IOException e) {    
        }
    } 
}
